﻿using System;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Media;

namespace ParallelUtils
{
    public class BitmapChunk
    {
        public int X { get { return rectangle.X; } }
        public int Y { get { return rectangle.Y; } }
        public int Width { get { return rectangle.Width; } }
        public int Height { get { return rectangle.Height; } }

        private Int32Rect rectangle;
        private byte[] colorData;

        /// <summary>
        /// Represents a rectangular chunk of bitmap
        /// </summary>
        /// <param name="x">horizontal offset inside the bitmap</param>
        /// <param name="y">vertical offset inside the bitmap</param>
        /// <param name="width">chunk width</param>
        /// <param name="height">chunk height</param>
        public BitmapChunk(int x, int y, int width, int height)
        {
            rectangle = new Int32Rect(x, y, width, height);
            colorData = new byte[4 * Width * Height];
        }

        public void DrawPixel(int x, int y, Color c)
        {
            var idx = 4 * (x + y * Width);
            colorData[idx++] = c.B;
            colorData[idx++] = c.G;
            colorData[idx++] = c.R;
        }
        public void UpdateBitmap(WriteableBitmap bitmap)
        {
            bitmap.Dispatcher.Invoke(new Action(() =>
            {
                bitmap.WritePixels(rectangle, colorData, 4 * Width, 0);
            }));
        }
    }
}
